package network;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;
    UdpEchoServer(int port) throws SocketException {
        //服务器申请一个指定的端口号
        socket = new DatagramSocket(port);
        //系统自动分配端口号
//        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        //不断的获取客户端的请求
        while (true) {
            //申请一个空间, 接收请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //此时的requestPacket.getLength()并不是4096, 而是接收值所占据数组的长度
            String response = process(request);
            //把返回的回应给数据包
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req=%s, resp=%s\n",
                    requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(1314);
        server.start();
    }
}
